Skip to content

fix(crashlytics): synchronize stored on-demand report paths across queues - #17127

Open
mghaznav wants to merge 4 commits into
mainfrom
ali/fix-cls-concurrent-access
Open

mghaznav wants to merge 4 commits into
mainfrom
ali/fix-cls-concurrent-access

Conversation

@mghaznav

Copy link
Copy Markdown
Contributor

Fixes #16805

Summary

When Crashlytics data collection is disabled, FIRCLSOnDemandModel stores recorded on-demand exception paths in storedActiveReportPaths on the com.google.firebase.crashlytics.on.demand queue, while FIRCLSExistingReportManager enumerates and clears storedActiveReportPaths on the com.google.firebase.crashlytics.startup queue without synchronization (#16805).

While that race is currently unreachable in production due to #16837 (where contextInitPromise blocks public API calls until startWithProfiling finishes), fixing #16837 in a follow-up PR will allow recordOnDemandExceptionModel: and sendUnsentReports / deleteUnsentReports to run concurrently. Landing this fix first ensures main remains thread-safe.

This PR also addresses two related edge cases in the same pre-consent on-demand path:

  1. Stale consent state across rate-limiting sleep(): FIRCrashlytics previously evaluated [self.dataArbiter isCrashlyticsCollectionEnabled] upfront before enqueueing onto FIRCLSOnDemandModel.operationQueue, which calls sleep(uploadDelay) for backoff. If a user enabled collection while operations were queued behind sleep(), waking operations saw the stale NO value and appended reports to storedActiveReportPaths after startup had already drained it.
  2. deleteUnsentReports cleanup: -[FIRCLSExistingReportManager deleteUnsentReports] previously deleted regular active, processing, and prepared reports, without draining or deleting storedActiveReportPaths.

Changes

  • FIRCLSOnDemandModel (FIRCLSOnDemandModel_Private.h, FIRCLSOnDemandModel.m):
    • Make _storedActiveReportPaths private and readonly (allocated once in init), replacing the exposed NSMutableArray property with -takeStoredActiveReportPaths and -storedActiveReportPathsSnapshot.
    • Guard all array reads and mutations with @synchronized(_storedActiveReportPaths). This acts strictly as an in-memory leaf lock (never held across sleep(), disk file deletion, stack unwinding, or cross-queue calls), avoiding stalls or deadlocks while guaranteeing exclusive ownership of each report path on disk.
    • Accept FIRCLSDataCollectionArbiter * in recordOnDemandExceptionIfQuota:withDataArbiter:usingExistingReportManager: (FIRCrashlytics.m) so each queued operation checks live consent when it executes.
  • FIRCLSExistingReportManager (FIRCLSExistingReportManager.m):
    • Update both sendUnsentReportsWithToken:asUrgent: and deleteUnsentReports to atomically drain [self.onDemandModel takeStoredActiveReportPaths].

Note on Supporting Changes in Existing Tests & Mocks

While validating the new multi-queue concurrency tests under Thread Sanitizer (-enableThreadSanitizer YES), a few pre-existing test/mock issues surfaced and are cleaned up in this PR so the TSan pass runs cleanly:

  • FIRCLSMockFileManager.m: Synchronized _fileSystemDict (NSMutableDictionary) and removeCount with @synchronized(self) to prevent mock-only dictionary data races when on.demand eviction and startup report processing access the mock file manager concurrently.
  • FIRCLSMockOnDemandModel.m: Switched mock report filename suffixes from arc4random_uniform(10000) to NSUUID to prevent filename collisions (birthday paradox) during high-iteration concurrency tests.
  • FIRCLSOnDemandModelTests.m (setUp / tearDown):
    • Removed the unused [contextManager setupContextWithReport:...] call in setUp. All tests in this suite use FIRCLSMockOnDemandModel (which does not read _firclsContext), and calling setupContextWithReport: per test registered duplicate _dyld_register_func_for_add_image callbacks (which dyld has no API to unregister) that raced on _firclsContext reallocation between tests under TSan.
    • Added queue draining (onDemandModel.operationQueue, managerData.dispatchQueue, existingReportManager.operationQueue), FIRCLSUserDefaults cleanup (so sticky setCrashlyticsCollectionEnabled: settings do not leak into subsequent test suites), and FIRCLSContextBaseDeinit() in tearDown.
  • FIRCrashlyticsTests.m:
    • Updated FIRCLSThreadTrackingOnDemandModel for the withDataArbiter: selector signature.
    • Replaced the non-atomic __block BOOL initSettled runloop spin-wait in setUp with XCTestExpectation, resolving a TSan data race on initSettled.

Testing

  • Added unit tests in FIRCLSOnDemandModelTests and FIRCLSReportManagerTests covering:
    • Concurrent multi-thread recordOnDemandExceptionIfQuota: (with > FIRCLSMaxUnsentReports evictions) alongside sendUnsentReportsWithToken: on the startup queue (#16805).
    • Enabling data collection while an operation is paused inside sleep(), verifying queued operations upload immediately on wakeup instead of stranding in storedActiveReportPaths.
    • deleteUnsentReports deleting stored on-demand report paths both directly and via FIRCLSReportManager.
    • Atomic claiming and clearing in takeStoredActiveReportPaths.
  • Ran the full FirebaseCrashlyticsUnit test suite (282 tests, 0 failures).
  • Ran FIRCLSOnDemandModelTests, FIRCLSReportManagerTests, and FIRCrashlyticsTests with Thread Sanitizer (-enableThreadSanitizer YES) (42 tests, 0 failures, 0 TSan warnings).

API Changes

None (internal FIRCLSOnDemandModel private category only).

@mghaznav mghaznav self-assigned this Nov 25, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

@mghaznav

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request addresses a thread-safety issue in Crashlytics where stored on-demand exception paths could be accessed concurrently from multiple queues when data collection is disabled. It introduces thread-safe accessors (takeStoredActiveReportPaths, storedActiveReportPathsSnapshot, and storeActiveReportPath:) synchronized on the stored paths array, and updates the existing report manager to properly clean up these reports in deleteUnsentReports. Additionally, unit tests and mocks have been updated and hardened for concurrency, including adding thread synchronization to FIRCLSMockFileManager. Feedback on the changes suggests clearing self.removeExpectation after capturing it in FIRCLSMockFileManager to prevent potential test failures from over-fulfilling the expectation.

@mghaznav
mghaznav marked this pull request as ready for review November 30, 2026 17:15

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant